import { Component, OnInit, Input } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl
} from '@angular/forms';
import { NzModalSubject } from 'ng-zorro-antd';

import { UsersService } from '../../services';
import { LocalstoreService } from '../../../shared/services';

@Component({
  selector: 'ege-new-user-form',
  templateUrl: './new-user-form.component.html',
  styleUrls: ['./new-user-form.component.scss']
})
export class NewUserFormComponent implements OnInit {

  isConfirmLoading = false;

  token = this.localstorageService.getItem('USER_TOKEN');

  validateForm: FormGroup;

  _submitForm() {
    for (const i in this.validateForm.controls) {
      if (this.validateForm.controls.hasOwnProperty(i)) {
        this.validateForm.controls[ i ].markAsDirty();
      }
    }

    if (this.validateForm.valid) {
      this.isConfirmLoading = true;

      const body = this.validateForm.value;
      // console.log(body);

      body.admin ? this.usersService
                      .newAdmin(body, this.token.id)
                      .subscribe((result) => {
                        // console.log(result);
                        this.onCreateSucceed(result);
                      }, (error) => {
                        this.onCreateFail();
                      }) :
                    this.usersService
                      .newUser(body, this.token.id)
                      .subscribe((result) => {
                        // console.log(result);
                        this.onCreateSucceed(result);
                      }, (error) => {
                        this.onCreateFail();
                      });
                  }
  }

  updateConfirmValidator() {
    /** wait for refresh value */
    setTimeout(_ => {
      this.validateForm.controls[ 'checkPassword' ].updateValueAndValidity();
    });
  }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls[ 'password' ].value) {
      return { confirm: true, error: true };
    }
  }

  onCreateSucceed(data: any) {
    this.isConfirmLoading = false;
    this.subject.next(data);
    this.subject.next('onOk');
  }

  onCreateFail() {
    this.isConfirmLoading = false;
  }

  handleCancel(e) {
    this.subject.destroy('onCancel');
  }

  constructor(
    private fb: FormBuilder,
    private subject: NzModalSubject,
    private usersService: UsersService,
    private localstorageService: LocalstoreService,
  ) {
    this.subject.on('onDestory', () => {
      // console.log('destroy');
    });
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      username         : [ null, [ Validators.required ] ],
      email            : [ null, [ Validators.email ] ],
      password         : [ null, [ Validators.required ] ],
      checkPassword    : [ null, [ Validators.required, this.confirmationValidator ] ],
      realname         : [ null ],
      realm            : [ null ],
      admin            : [ false ],
    });
  }

  getFormControl(name) {
    return this.validateForm.controls[ name ];
  }

}
